/**
 * Created by Weizehua on 2017/1/21.
 */

// var t = require("./topClient");
let TopClient = require("./topClient").TopClient;
import {Singleton} from "ts.di";

@Singleton()
export class AliDayuSMS {
    constructor(private appKey: string, private appSecret: string, private signName: string) {
        this.client = new TopClient({
            'appkey': this.appKey,
            'appsecret': this.appSecret,
            'REST_URL': 'http://gw.api.taobao.com/router/rest '
        });
    }

    sendCaptcha(phone: string, availableMinutes: number): Promise<string> {
        return new Promise<string>((resolve, reject) => {
            let captcha = AliDayuSMS.generateCaptcha();
            this.client.execute('alibaba.aliqin.fc.sms.num.send', {
                'extend': '',
                'sms_type': 'normal',
                'sms_free_sign_name': this.signName,
                'sms_param': {captcha: captcha, minutes: String(availableMinutes), app: this.signName},
                'rec_num': phone,
                'sms_template_code': "SMS_43305110"
            }, function (error, response) {
                if (!error) {
                    return resolve(captcha);
                }
                else {
                    reject(error);
                }
            });
        });
    }

    private static generateCaptcha(): string {
        return String(Math.floor(Math.random() * 900001) + 100000);
    }

    private client;
}

